package org.wang.generalcode.modules.exam.pdf;

import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.property.TextAlignment;
import org.springframework.util.StringUtils;

import java.net.MalformedURLException;
import java.net.URL;

public class HeaderMarkerEventHandler implements IEventHandler {
    /**
     * pdf字体
     */
    private final PdfFont pdfFont;

    /**
     * 页眉显示
     */
    private final String title;

    /**
     * logo地址
     */
    private String logoUrl;

    public HeaderMarkerEventHandler(PdfFont pdfFont, String title) {
        this.pdfFont = pdfFont;
        this.title = title;
    }

    public HeaderMarkerEventHandler(PdfFont pdfFont, String title, String logoUrl) {
        this.pdfFont = pdfFont;
        this.title = title;
        this.logoUrl = logoUrl;
    }

    @Override
    public void handleEvent(Event event) {
        PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        PdfDocument pdf = docEvent.getDocument();
        PdfPage page = docEvent.getPage();
        Rectangle pageSize = page.getPageSize();
        PdfCanvas pdfCanvas = new PdfCanvas(page.getLastContentStream(), page.getResources(), pdf);
        Canvas canvas = new Canvas(pdfCanvas, pageSize);
        float x = pageSize.getRight() - 60;
        float y = pageSize.getTop() - 32;
        Paragraph p = new Paragraph(title)
                .setFontSize(9)
                .setFont(pdfFont);
        // 显示在顶部右侧位置
        canvas.showTextAligned(p, x, y, TextAlignment.RIGHT);

        if (!StringUtils.isEmpty(logoUrl)) {
            try {
                URL url = new URL(logoUrl);
                Image logo = new Image(ImageDataFactory.create(url));
                logo.scaleAbsolute(100, 20);
                logo.setMarginLeft(30);
                logo.setMarginTop(15);
                canvas.add(logo);
            } catch (MalformedURLException e) {
                System.out.println("logo 无法解析: " + logoUrl);
            }
        }
        canvas.close();
    }
}
